package cn.ratel.db;

import cn.ratel.component.Plugins;
import cn.ratel.db.ds.DataSourceProvider;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ActiveRecordPlugin implements Plugins.Plugin {
	private DataSourceProvider dataSourceProvider;

	public ActiveRecordPlugin(DataSourceProvider dataSourceProvider) {
		this.dataSourceProvider = dataSourceProvider;
	}

	@Override
	public void start() {
		DbKit.setDataSourceProvider(dataSourceProvider);
		Connection conn = DbKit.getConnection();
		try {
			DatabaseMetaData metaData = conn.getMetaData();
			for (Class clazz : TableBuilder.getModels()) {
				Table table = new Table(clazz);
				ResultSet rs = metaData.getColumns(null, null, table.name, null);
				while (rs.next()) {
					TableBuilder.addColumn(table, rs);
				}
				TableBuilder.addTable(table);
				rs.close();
			}
		} catch (SQLException e) {
			throw new RuntimeException("start ActiveRecordPlugin error :", e);
		} finally {
			DbKit.close(conn);
		}
	}

	@Override
	public void stop() {

	}

}
